package com.soloyogame.anitoys.my.web.controller.front.favorite;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.soloyogame.anitoys.core.Services;
import com.soloyogame.anitoys.db.commond.Account;
import com.soloyogame.anitoys.db.commond.CartInfo;
import com.soloyogame.anitoys.db.commond.Favorite;
import com.soloyogame.anitoys.db.commond.FavoriteBusiness;
import com.soloyogame.anitoys.db.commond.FavoriteBusinessResult;
import com.soloyogame.anitoys.db.commond.FavoriteResult;
import com.soloyogame.anitoys.db.commond.Product;
import com.soloyogame.anitoys.my.web.controller.front.FrontBaseController;
import com.soloyogame.anitoys.my.web.controller.front.util.RequestHolder;
import com.soloyogame.anitoys.service.BusinessService;
import com.soloyogame.anitoys.service.FavoriteBusinessService;
import com.soloyogame.anitoys.service.FavoriteService;
import com.soloyogame.anitoys.service.HelpService;
import com.soloyogame.anitoys.service.ProductService;
import com.soloyogame.anitoys.util.cache.RedisCacheProvider;


/**
 * 收藏（商品、店铺）
 * @author wuxiongxiong 2015年12月1日下午6:48:11
 */
@Controller("favoriteController")
@RequestMapping("favorite")
public class FavoriteAction extends FrontBaseController<Favorite> 
{
	private static final long serialVersion = 1L;
	private static final Logger logger = LoggerFactory
			.getLogger(FavoriteAction.class);

	@Autowired
	private FavoriteService favoriteService;
	@Autowired
	private ProductService productService;
	@Autowired
	private FavoriteBusinessService favoriteBusinessService;
	@Autowired
	private BusinessService businessService ;
	@Autowired
	private RedisCacheProvider redisCacheProvider;
	@Autowired
    private HelpService helpService;
	
	/**
	 * 添加收藏商品信息
	 * @return
	 */
	@RequestMapping("addFavoriteProduct")
	public String addFavoriteProduct(ModelMap model) 
	{
		logger.info("FavoriteAction.addFavoriteProduct...");

		Favorite fav = new Favorite();
		HttpServletRequest request = RequestHolder.getRequest();
		String productID = request.getParameter("id"); // 获取商品ID
		if (StringUtils.isEmpty(productID)) 
		{
			throw new NullPointerException("参数错误！");
		} 
		else 
		{
			fav.setProductId(Integer.parseInt(productID));
		}

		// 获取用户登录ID，并判断用户是否登录，若没登录，需返回登录
		Account account = getLoginAccount();
		if (account == null || StringUtils.isBlank(account.getAccount())) 
		{
			return page_toLoginRedirect;
		}
		fav.setId("0");
		fav.setUserId(account.getAccountId());
		// 查询收藏的商品信息，如：关键词、描述
		Product product = new Product();
		product = productService.selectproduct(Integer.parseInt(productID));

		fav.setDescription(product.getDescription());
		fav.setKeywords(product.getKeywords());
		fav.setName(product.getName());
		int isNo = 1;
		Favorite favResult = favoriteService.searchByPid(fav) ;
		if ( favResult == null ) 
		{
			isNo = favoriteService.insert(fav);
		} 
		else 
		{						
			favoriteService.update(fav);
			isNo = 0;
		}

		// isFavorite=0表示该商品已收藏即收藏成功，isFavorite=1表示该商品还未收藏即收藏失败
		int isFavorite = 1;
		if (isNo == 0) 
		{
			isFavorite = 0;
		}
		model.addAttribute("isFavorite", isFavorite);
		return "forward:/product/" + productID;
	}
	
	/**
	 * 批量添加收藏商品信息
	 * @return
	 */
	@RequestMapping("addFavoriteProducts")
	public String addFavoriteProducts(ModelMap model,String[] ids) 
	{
		logger.info("FavoriteAction.addFavoriteProduct...");

		Favorite fav = new Favorite();
		HttpServletRequest request = RequestHolder.getRequest();
		for(int i=0;i<ids.length;i++)
		{
			String productID = ids[i];       // 获取商品ID
			if (StringUtils.isEmpty(productID)) 
			{
				throw new NullPointerException("参数错误！");
			} 
			else 
			{
				fav.setProductId(Integer.parseInt(productID));
			}
			// 获取用户登录ID，并判断用户是否登录，若没登录，需返回登录
			Account account = getLoginAccount();
			if (account == null || StringUtils.isBlank(account.getAccount())) 
			{
				return page_toLoginRedirect;
			}
			fav.setId("0");
			fav.setUserId(account.getAccountId());
			// 查询收藏的商品信息，如：关键词、描述
			Product product = new Product();
			product = productService.selectproduct(Integer.parseInt(productID));

			fav.setDescription(product.getDescription());
			fav.setKeywords(product.getKeywords());
			fav.setName(product.getName());
			int isNo = 1;
			
			
			 Favorite favResult = favoriteService.searchByPid(fav) ;
			if ( favResult == null ) 
			{
				isNo = favoriteService.insert(fav);
			} 
			else 
			{						
				favoriteService.update(fav);
				isNo = 0;
			}

			// isFavorite=0表示该商品已收藏即收藏成功，isFavorite=1表示该商品还未收藏即收藏失败
			int isFavorite = 1;
			if (isNo == 0) 
			{
				isFavorite = 0;
			}
			model.addAttribute("isFavorite", isFavorite);
		}
		return "redirect:/cart/cart.html";
	}


	/**
	 * 取消收藏商品信息
	 * @param model
	 * @return
	 */
	@RequestMapping("deleteFavoriteProduct")
	public String deleteFavoriteProduct(ModelMap model) 
	{
		logger.info("FavoriteAction.deleteFavoriteProduct...");

		Favorite e = new Favorite();
		HttpServletRequest request = RequestHolder.getRequest();
		String productID = request.getParameter("productId"); // 获取商品ID
		if (StringUtils.isEmpty(productID)) 
		{
			throw new NullPointerException("参数错误！");
		} 
		else 
		{
			e.setProductId(Integer.parseInt(productID));
		}

		Account account = getLoginAccount();
		if (account == null || StringUtils.isBlank(account.getAccount()))
		{
			return page_toLoginRedirect;
		}
		e.setUserId(account.getAccountId());

		int isdelete = favoriteService.delete(e);

		
		//取消收藏是否成功标志
		boolean isDeleteSuccess = false ;
		if (isdelete == 1) {
			isDeleteSuccess = true;
		}
		model.addAttribute("isDeleteSuccess", isDeleteSuccess);		
		return "forward:/favorite/searchUserFavoritePro";
	}
	
	
	
	/**
	 * 批量取消收藏的商品
	 * @param model
	 * @return
	 */
	@RequestMapping("deleteFavoriteProductList")
	public String deleteFavoriteProductList(ModelMap model,String[] ids)
	{
		logger.info("FavoriteAction.addFavoriteProduct...");

		Favorite e = new Favorite();
		HttpServletRequest request = RequestHolder.getRequest();
		
		Account account = getLoginAccount();
		if (account == null || StringUtils.isBlank(account.getAccount())) 
		{
			return page_toLoginRedirect;
		}
		e.setUserId(account.getAccountId());
		
		for(int i=0;i<ids.length;i++)
		{
			String productID = ids[i];       // 获取商品ID
			if (StringUtils.isEmpty(productID)) 
			{
				throw new NullPointerException("参数错误！");
			} 
			else 
			{
				e.setProductId(Integer.parseInt(productID));
			}
			
			int isdelete = favoriteService.delete(e);
			
			//取消收藏是否成功标志
			boolean isDeleteSuccess = false ;
			if (isdelete == 1)
			{
				isDeleteSuccess = true;
			}
			model.addAttribute("isDeleteSuccess", isDeleteSuccess);	
		}
	
		return "forward:/favorite/searchUserFavoritePro";
	}
	

	/**
	 * 查询用户所有收藏的商品-根据用户ID
	 * @return
	 */
	@RequestMapping("searchUserFavoritePro")
	public String searchFavoriteProduct(ModelMap model) 
	{
		logger.info("FavoriteAction.searchFavoriteProduct...");
		Favorite fav = new Favorite();
		List<FavoriteResult> favPro = new ArrayList();
		Account account = getLoginAccount();
		if (account == null || StringUtils.isBlank(account.getAccount())) 
		{
			return page_toLoginRedirect;
		}
		int productCount=productService.selectProductCount();
		model.addAttribute("productCount", productCount);
		fav.setUserId(account.getAccountId());
		favPro = favoriteService.searchUserFavPro(fav);
		model.addAttribute("favPro", favPro);
		return "/account/favorite";
	}

	/**
	 * 收藏店铺
	 * @param model
	 * @return
	 */
	@RequestMapping("addFavoriteBusi")
	public String addFavoriteBusi(ModelMap model) 
	{
		logger.info("FavoriteAction.addFavoriteBusi...");
		FavoriteBusiness favBusi = new FavoriteBusiness();

		// 获取用户ID
		Account account = getLoginAccount();
		if (account == null || StringUtils.isBlank(account.getAccount()))
		{
			return page_toLoginRedirect;
		}		
		favBusi.setAccountId(account.getAccountId());
		int isFavoriteBusiness=0;
		HttpServletRequest request = RequestHolder.getRequest();
		String businessId = request.getParameter("businessId"); 	// 获取店铺ID
		String productID = request.getParameter("id"); 				// 获取商品ID
//		businessId = "5" ;  //测试收藏店铺
		if(businessId != null && businessId != "" )
		{  				
			//判断前台传入的店铺ID是否为空
			favBusi.setBusinessId(businessId) ;
			FavoriteBusinessResult favoriteBusinessResult = new FavoriteBusinessResult() ;
			favoriteBusinessResult.setBusinessId(businessId); 
			FavoriteBusinessResult BusinessInfo = new FavoriteBusinessResult() ;
			BusinessInfo = favoriteBusinessService.searchBusinessInfo(favoriteBusinessResult) ;

			//查询该店铺是否已收藏过
			List<FavoriteBusinessResult> listResult = favoriteBusinessService.searchFavoriteBusinessByAccountBusiID(favBusi) ;
			
			if(BusinessInfo!=null)
			{ 
				//判断店铺是否还存在，如果存在，则收藏
				favBusi.setBusinessName(BusinessInfo.getBusinessName());
				if(listResult == null ||listResult.isEmpty())
				{
					isFavoriteBusiness=favoriteBusinessService.insert(favBusi);
				}
				else
				{
					favBusi.setId(listResult.get(0).getId());
					favoriteBusinessService.update(favBusi) ;
					isFavoriteBusiness=0;
				}
				
			}
			else
			{
				logger.info("店铺已不存在！");
			}
		
		}
		else
		{
			logger.info("店铺ID为空！");
		}		
		model.addAttribute("isFavoriteBusiness", isFavoriteBusiness);
		return "forward:/product/"+ productID;

	}

	/**
	 * 取消店铺收藏
	 * @return
	 */
	@RequestMapping("deleteUserFavoriteBusiness")
	public String deleteUserFavoriteBusiness(ModelMap model)
	{
		logger.info("deleteUserFavoriteBusiness...");
		FavoriteBusiness favBusi = new FavoriteBusiness();

		// 获取用户ID
		Account account = getLoginAccount();
		if (account == null || StringUtils.isBlank(account.getAccount())) 
		{
			return page_toLoginRedirect;
		}		
		favBusi.setAccount(account.getAccount());
		
		HttpServletRequest request = RequestHolder.getRequest();
		String businessId = request.getParameter("businessId"); 	// 获取店铺ID
		if (businessId != null) 
		{
			favBusi.setBusinessId(businessId);
		}
		int isdelete = favoriteBusinessService.delete(favBusi) ;						
		//取消收藏是否成功标志
		boolean isDeleteSuccess = false ;
		if (isdelete == 1) 
		{
			isDeleteSuccess = true;
		}
		model.addAttribute("isDeleteSuccess", isDeleteSuccess);		
		return "forward:/favorite/searchUserFavoriteBusi";
	}
	
	/**
	 * 批量取消店铺收藏
	 * @return
	 */
	@RequestMapping("deleteFavoriteBusinessses")
	public String deleteFavoriteBusinessses(ModelMap model ,String[] ids)
	{
		logger.info("deleteUserFavoriteBusiness...");
		FavoriteBusiness favBusi = new FavoriteBusiness();

		// 获取用户ID
		Account account = getLoginAccount();
		if (account == null || StringUtils.isBlank(account.getAccount())) 
		{
			return page_toLoginRedirect;
		}		
		favBusi.setAccountId(account.getAccountId());
		
		//取消收藏是否成功标志
		boolean isDeleteSuccess = false ;		
		for(int i = 0 ; i<ids.length ; i++)
		{
			String businessId = ids[i] ;
			if (businessId != null) 
			{
				favBusi.setBusinessId(businessId);
			}
			int isdelete = favoriteBusinessService.delete(favBusi) ;
			if (isdelete == 1) 
			{
				isDeleteSuccess = true;
			}
		}
		model.addAttribute("isDeleteSuccess", isDeleteSuccess);		
		return "forward:/favorite/searchUserFavoriteBusi";
		
	}
	
	/**
	 * 查询用户所有收藏的店铺-根据用户ID
	 * @return
	 */
	@RequestMapping("searchUserFavoriteBusi")
	public String searchUserFavoriteBusi(ModelMap model) 
	{
		logger.info("FavoriteAction.searchUserFavoriteBusi...");
		FavoriteBusiness favBusi = new FavoriteBusiness();
		// 获取用户ID
		Account account = getLoginAccount();
		if (account == null || StringUtils.isBlank(account.getAccount())) 
		{
			return page_toLoginRedirect;
		}
		List<Product> productList = new ArrayList<Product>();
		CartInfo cartInfo = null;
		if(account==null)
		{
			cartInfo = (CartInfo) redisCacheProvider.get("myCart");
		}
		else
		{
			cartInfo = (CartInfo) redisCacheProvider.get("user_"+account.getId()+"Cart");
		}
		if(cartInfo!=null)
		{
			productList = cartInfo.getProductList();
		} 
		else 
		{
			cartInfo = new CartInfo();
		}
		int productCount=productService.selectProductCount();
		
		model.addAttribute("cartInfo", cartInfo);
		model.addAttribute("productCount", productCount);
		model.addAttribute("productList", productList);
		favBusi.setAccountId(account.getAccountId());

		List<FavoriteBusinessResult> favBusiShowList = new ArrayList();
		// 查询用户所有收藏店铺
		favBusiShowList = favoriteBusinessService.searchFavoriteBusinessID(favBusi);

		List<FavoriteBusinessResult> favBusiList = new ArrayList();
		// 查询用户收藏店铺名下的所有商品
		favBusiList = favoriteBusinessService.searchFavoriteBusiness(favBusi);
				
		if (favBusiList != null && favBusiShowList != null) 
		{
			for (FavoriteBusinessResult favoriteBusinessResult : favBusiShowList) 
			{
				for (FavoriteBusinessResult favoriteBusinessShow : favBusiList) 
				{
					if (favoriteBusinessShow.getBusinessId().equals(favoriteBusinessResult.getBusinessId())) 
					{
						Product productTemp = new Product();
						productTemp.setId(favoriteBusinessShow.getProductID());
						productTemp.setPicture(favoriteBusinessShow.getPicture());
						productTemp.setName(favoriteBusinessShow.getProductName());
						favoriteBusinessResult.getBusinessProduct().add(productTemp);
					}
				}

			}
		}
		else
		{
			logger.info("无收藏店铺");
		}
		model.addAttribute("favBusiShowList", favBusiShowList);
		return "/account/favoriteBusiness";
	}

		
	@Override
	public Services<Favorite> getService() 
	{
		return null;
	}

}
